<template>
    <div class="attribute-issue-modal-wrapper">
        <el-dialog :model-value="props.value" :title="dialog.title" :width="dialog.width" destroy-on-close>
            <DataGrid :auto-load="autoLoad" border :native="true">
                <template #toolbar-search>
                    <div class="query-from-box">
                        <el-form :model="queryData">
                            <el-form-item>
                                <el-tree-select
                                    v-model="queryData.deviceNo"
                                    :data="deviceComponentList"
                                    check-strictly
                                    :props="defaultProps"
                                    :render-after-expand="false"
                                    placeholder="所属设备/组件"
                                    @change="onDeviceComponentChange"
                                    clearable
                                />
                            </el-form-item>
                            <el-form-item>
                                <el-select
                                    v-model="queryData.selects"
                                    placeholder="属性名称"
                                    multiple
                                    collapse-tags
                                    collapse-tags-tooltip
                                    clearable
                                >
                                    <el-option
                                        v-for="item in attributeListMap[queryData.deviceNo] || []"
                                        :key="item.id"
                                        :label="item.displayName"
                                        :value="item.attributeName"
                                    />
                                </el-select>
                            </el-form-item>
                            <el-form-item style="width: 320px">
                                <el-date-picker
                                    v-model="beginTime"
                                    type="datetimerange"
                                    unlink-panels
                                    range-separator="-"
                                    start-placeholder="更新时间起"
                                    end-placeholder="更新时间止"
                                    value-format="YYYY-MM-DD HH:mm:ss"
                                    format="YYYY-MM-DD HH:mm:ss"
                                    :default-time="defaultTime"
                                    @change="changeDataPicker"
                                    :editable="true"
                                    :clearable="false"
                                />
                            </el-form-item>
                        </el-form>
                    </div>
                </template>
                <template #default>
                    <el-table-column
                        type="index"
                        label="序号"
                        width="60"
                        align="center"
                        fixed
                        v-if="tableData.length"
                    />
                    <el-table-column label="采集时间" fixed v-if="tableData.length && tableData[0].采集时间">
                        <template #default="scope">
                            <span style="white-space: nowrap">
                                {{ scope.row.采集时间 }}
                            </span>
                        </template>
                    </el-table-column>
                    <template v-for="(value, key) in tableData[0]">
                        <el-table-column
                            v-if="String(key) !== '采集时间'"
                            :key="key"
                            :label="String(key)"
                            show-overflow-tooltip
                        >
                            <template #default="scope">
                                <span style="white-space: nowrap">
                                    {{ scope.row[key] }}
                                </span>
                            </template>
                        </el-table-column>
                    </template>
                </template>
            </DataGrid>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="props.close">关闭</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { IoTDeviceService, modelThingService } from '@great/services';
import { reactive } from 'vue';
import { DataGrid } from '@great/components';
import type { PopupBoxProps } from '@great/utils';
import { useRoute } from 'vue-router';

const route = useRoute();
interface IProps extends PopupBoxProps {
    deviceDetail: Record<string, any>;
}
const props = defineProps<IProps>();

interface Dialog {
    title: string;
    width: number;
    detail?: Record<string, any>;
}
const dialog = reactive<Dialog>({
    title: '属性历史',
    width: 1200,
    detail: undefined
});
// 查询条件
const queryData = ref({
    proDeviceNo: props.deviceDetail?.deviceNo,
    productObject: props.deviceDetail?.objectName,
    deviceNo: '',
    selects: [],
    beginTime: '',
    endTime: ''
});
const defaultProps = {
    label: 'deviceName',
    value: 'deviceNo'
};
const deviceComponentList = ref<any>([]);
const attributeListMap = ref<any>({});
const defaultTime = ref<[Date, Date]>([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]);

const beginTime = ref([
    `${new Date()
        .toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit'
        })
        .replace(/\//g, '-')} 00:00:00`,
    `${new Date()
        .toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit'
        })
        .replace(/\//g, '-')} 23:59:59`
]);
let tableData = ref<any>([]);
const autoLoad = reactive({
    debounce: true,
    reloadDeps: [queryData],
    onLoad: async (current, size) => {
        const res = await IoTDeviceService.history({
            queryPage: {
                currentPage: current,
                pageSize: size,
                pageSearchCount: true
            },
            ...queryData.value
        });
        tableData.value = JSON.parse(JSON.stringify(res.data.records));
        return { data: res.data.records, total: res.data.total };
    }
});
const changeDataPicker = () => {
    if (beginTime.value && beginTime.value.length) {
        queryData.value.beginTime = beginTime.value[0];
        queryData.value.endTime = beginTime.value[1];
    } else {
        queryData.value.beginTime = '';
        queryData.value.endTime = '';
    }
};
const getChoiceDevice = (tree, deviceNo) => {
    if (!Array.isArray(tree)) return null;
    for (const node of tree) {
        if (node.deviceNo === deviceNo) {
            return node;
        }
        if (Array.isArray(node.children) && node.children.length > 0) {
            const found = getChoiceDevice(node.children, deviceNo);
            if (found) {
                return found;
            }
        }
    }
    return null;
};
const onDeviceComponentChange = () => {
    queryData.value.selects = [];
    let choiceDevice = getChoiceDevice(deviceComponentList.value, queryData.value.deviceNo);
    getAttributeList(choiceDevice);
};
const getAttributeList = async choiceDevice => {
    if (attributeListMap.value[queryData.value.deviceNo]) return;
    //   获取设备属性列表
    modelThingService.attribute
        .getList({
            objectName: choiceDevice ? choiceDevice.objectName : '',
            size: 1000000
        })
        .then(result => {
            attributeListMap.value[queryData.value.deviceNo] = result.data.records || [];
        });
};
// 获取设备组件列表
const getDeviceComponentList = async () => {
    const res = await IoTDeviceService.getTreeDevice({
        id: props.deviceDetail?.id || route.params.id,
        enabled: true
    });
    deviceComponentList.value = res.data;
};
const init = () => {
    getDeviceComponentList();
    changeDataPicker();
};
init();
</script>
<style scoped lang="scss">
.attribute-issue-modal-wrapper {
    .query-from-box {
        display: flex;
        align-items: center;
        .el-form {
            display: flex;
            .el-form-item {
                margin-bottom: 0;
                width: 192px;
            }
            .el-form-item + .el-form-item {
                margin-left: 10px;
            }
        }
    }
    :deep(.data-grid) {
        .table-item-tag {
            display: flex;
        }
        .table-item-status {
            display: flex;
            align-items: center;
            &::before {
                content: '';
                width: 6px;
                height: 6px;
                display: inline-block;
                border-radius: 50%;
                margin-right: 5px;
            }
        }
        .table-item-status[status='成功'] {
            &::before {
                background-color: #67c23a;
            }
        }
        .table-item-status[status='失败'] {
            &::before {
                background-color: #f56c6c;
            }
        }
    }
}
</style>
